import {View, Text, Image, Button, ScrollView} from '@tarojs/components';
import Taro from '@tarojs/taro';
import React from 'react';
import {connect} from 'react-redux';
import * as T from './types';
import './index.less';
import actions from './actions';
import {store2Props} from './selectors';
import bgImg from '@/assets/image/my/my_bg.png';
import setImg from '@/assets/image/my/set.png';
import uesrImg from '@/assets/image/my/uesr_pic.png';
import msClose from '@/assets/image/my/close.png';
import vipImg from '@/assets/image/my/vip.png';
import ordinaryImg from '@/assets/image/my/ordinary.png';
import blueImg from '@/assets/image/my/blue.png';
import redImg from '@/assets/image/my/red.png';
import twoImg from '@/assets/image/my/two.png';
import calendarImg from '@/assets/image/my/calendar.png';
import goldImg from '@/assets/image/my/gold.png';
import TopBox from './components/topBox';
import CenterBox from './components/centerBox';
import OrderBox from './components/order';
import ToolsBox from './components/toolsBox';
import {AtModal, AtModalHeader, AtModalContent, AtModalAction} from 'taro-ui';
import AdvModal from '@/pages/common/adv-modal/adv-modal';
import {fetchModal, handleUrl, setModalShow, pvUvStatics} from 'wmkit';
import BlacklistModel from '@/pages/common/blacklist-model';
import api from 'api';
import pointBg from '@/assets/image/userCenterPage/pointBg.png';
import signBg from '@/assets/image/userCenterPage/signBg.png';

//@ts-ignore
actions().actions.loadReducer();
//@ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class TaroUserCenter extends React.Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      isModalFlag: false,
      imgUrl: '',
      jumpPage: {},
      show: true,
      showTip: true,
      navBarHeight: 0,
      windowHeight: 0,
    };
  }

  async componentWillMount() {
    if (__TARO_ENV !== 'h5') {
      Taro.showShareMenu({
        withShareTicket: true,
      });
    }
    this.updateModalStatus('');
  }

  componentDidMount() {
    this.getNavHeight();
  }

  componentDidShow() {
    this.props.actions.init();
    const title = Taro.getStorageSync('taskModel');
    if (title) {
      Taro.showToast({
        title,
        icon: 'none',
      });
      Taro.removeStorageSync('taskModel');
    }
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  async onShareAppMessage() {
    //触发分享，任务完成
    let task = Taro.getStorageSync('task');
    if (task) {
      task = JSON.parse(task);
      let id = task.id;
      const result = await api.TaskCenterController.completedTask({id});
      // setTimeout(()=>{
      // Taro.showToast({
      //   title: `获得${task.taskInfoVO.rewardType == 0 ? task.taskInfoVO.rewardPoints : ""}${["积分", "优惠券", "实物商品"][task.taskInfoVO.rewardType]}${task.taskInfoVO.rewardType == 2 ? "请到我的-我的奖励中填写收货地址" : ""}`,
      //   icon: 'none',
      // });
      Taro.removeStorageSync('task');
      Taro.setStorageSync(
        'taskModel',
        `获得${task.taskInfoVO.rewardType == 0 ? task.taskInfoVO.rewardPoints : ''}${
          ['积分', '优惠券', '实物商品'][task.taskInfoVO.rewardType]
        }${task.taskInfoVO.rewardType == 2 ? '请到我的-我的奖励中填写收货地址' : ''}`,
      );
      // },5000)
    }
    let wechatShareInfo = JSON.parse(Taro.getStorageSync('wechatShareInfo'));
    return {
      title: wechatShareInfo.title,
      imageUrl: wechatShareInfo.imgUrl[0].url,
    };
  }

  async updateModalStatus(id) {
    const res = await fetchModal('personalCenter');
    let popupId = null;
    if (!id && res && res.length > 0) {
      popupId = res[0].popupId;
    } else {
      popupId = id;
    }
    const flagParams = await setModalShow(res, 'personalCenter', popupId);
    this.setState(
      {
        isModalFlag: flagParams.showFlag,
        imgUrl: flagParams.imgUrl,
        jumpPage: (flagParams.jumpPage && JSON.parse(flagParams.jumpPage)) || '',
        nextPopupId: flagParams.nextPopupId,
      },
      () => {
        if (this.state.nextPopupId && !this.state.isModalFlag) {
          this.isGo(this.state.nextPopupId);
        }
      },
    );
  }
  async isGo(id) {
    await this.updateModalStatus(id);
  }
  handleClose() {
    this.setState({isModalFlag: false}, async () => {
      if (this.state.nextPopupId) {
        await this.updateModalStatus(this.state.nextPopupId);
      }
    });
  }

  getNavHeight() {
    let menuButtonObject = Taro.getMenuButtonBoundingClientRect();
    var sysinfo = Taro.getSystemInfoSync();
    let windowHeight = sysinfo.windowHeight;
    let statusBarHeight = sysinfo.statusBarHeight;
    let menuBottonHeight = menuButtonObject.height;
    let menuBottonTop = menuButtonObject.top;
    let navBarHeight = statusBarHeight + menuBottonHeight + (menuBottonTop - statusBarHeight) * 2;
    this.setState({
      navBarHeight,
      windowHeight,
    });
  }

  render() {
    let itemStr = Taro.getStorageSync('b2b-wechat@login');
    let {navBarHeight, show, showTip} = this.state;
    let {
      main: {
        isLogin,
        visible,
        customer,
        pointsAvailable,
        totalSignDays,
        isAquamarineMember, //是否蓝晶会员标志 false：否，true：是
        isCrystalMember, //是否赤晶会员标志 false：否，true：是
        memberDays, //已成为会员多少天-会员时才会展示，非会员无需展示
        endTime, //会员有效期至
        dualMembershipCardNumber, //双会员卡号
        aquamarineMembershipCardNumber, //蓝晶会员卡号
        crystalMembershipCardNumber, //赤晶会员卡号
        blacklistModel, //是否在黑名单里
        rankBadgeImg, //等级勋章
      },
      actions: {action},
    } = this.props;
    return (
      <ScrollView className="pagesUserCenter" scrollY>
        <Image className="banner" src={bgImg} mode="widthFix" />
        <View className="headerBox" style={{paddingTop: navBarHeight}}>
          <View className="userBox">
            {!isLogin ? (
              <View
                className="headPic"
                onClick={(e) => {
                  e.stopPropagation();
                  Taro.navigateTo({
                    url: '/pages/package-C/login/login/index',
                  });
                }}
              >
                <Image className="uesrImg" src={uesrImg} mode="aspectFill" />
              </View>
            ) : (
              <View
                className="headPic"
                onClick={(e) => {
                  e.stopPropagation();
                  if (Taro.getStorageSync('blacklistModel')) {
                    action.commonChange('main.blacklistModel', true);
                    return;
                  }
                  Taro.navigateTo({
                    url: '/pages/package-C/personal/index',
                  });
                }}
              >
                <Image
                  className="uesrImg"
                  src={customer?.pictureUrl ? customer?.pictureUrl : uesrImg}
                  mode="aspectFill"
                />
              </View>
            )}
            <View className="userNameBox">
              <View className="topBoxFirst">
                {isLogin ? (
                  <View
                    className="topBox"
                    onClick={(e) => {
                      e.stopPropagation();
                      if (Taro.getStorageSync('blacklistModel')) {
                        action.commonChange('main.blacklistModel', true);
                        return;
                      }
                      Taro.navigateTo({
                        url: '/pages/package-C/personal/index',
                      });
                    }}
                  >
                    <Text className="userName">{customer?.name || '微信用户'}</Text>
                    {rankBadgeImg && (
                      <Image
                        className="levelImg"
                        src={rankBadgeImg}
                        mode="widthFix"
                        onClick={(e) => {
                          e.stopPropagation();
                          if (Taro.getStorageSync('blacklistModel')) {
                            action.commonChange('main.blacklistModel', true);
                            return;
                          }
                          Taro.navigateTo({
                            url: '/pages/package-C/growthSetting/index',
                          });
                        }}
                      />
                    )}
                  </View>
                ) : (
                  <View
                    onClick={(e) => {
                      e.stopPropagation();
                      Taro.navigateTo({
                        url: '/pages/package-C/login/login/index',
                      });
                    }}
                  >
                    <Text className="userName">登录/注册</Text>
                  </View>
                )}
                <View
                  onClick={(e) => {
                    e.stopPropagation();
                    if (!itemStr) {
                      Taro.navigateTo({
                        url: '/pages/package-C/login/login/index',
                      });
                      return;
                    }
                    if (Taro.getStorageSync('blacklistModel')) {
                      action.commonChange('main.blacklistModel', true);
                      return;
                    }
                    Taro.navigateTo({
                      url: '/pages/package-C/setting/index',
                    });
                  }}
                >
                  <Image className="setting" src={setImg} mode="widthFix" />
                </View>
              </View>
              <View className="bottom">
                <Image
                  className="userType"
                  src={
                    isAquamarineMember && isCrystalMember //双会员
                      ? twoImg
                      : isAquamarineMember && !isCrystalMember //蓝晶会员
                      ? blueImg
                      : !isAquamarineMember && isCrystalMember //赤晶会员
                      ? redImg
                      : ordinaryImg //普通用户
                  }
                  mode="heightFix"
                />
                <View
                  className="signBg"
                  style={{backgroundImage: `url(${signBg})`}}
                  onClick={(e) => {
                    e.stopPropagation();
                    if (Taro.getStorageSync('blacklistModel')) {
                      action.commonChange('main.blacklistModel', true);
                      return;
                    }
                    if (Taro.getStorageSync('blacklistModel')) {
                      action.commonChange('main.blacklistModel', true);
                      return;
                    }
                    Taro.navigateTo({
                      url: '/pages/package-C/points-mall/index',
                    });
                  }}
                >
                  <Image className="calendarImg" src={calendarImg} mode="widthFix" />
                  <View className="text">已签到 {totalSignDays} 天</View>
                </View>
              </View>
            </View>
          </View>
          <View className="cardPoint">
            <View className="card">
              {
                isAquamarineMember && isCrystalMember //双会员
                  ? dualMembershipCardNumber
                  : isAquamarineMember && !isCrystalMember //蓝晶会员
                  ? aquamarineMembershipCardNumber
                  : !isAquamarineMember && isCrystalMember //赤晶会员
                  ? crystalMembershipCardNumber
                  : '' //普通用户不显示卡号
              }
            </View>
            <View
              className="point"
              style={{backgroundImage: `url(${pointBg})`}}
              onClick={(e) => {
                e.stopPropagation();
                if (Taro.getStorageSync('blacklistModel')) {
                  action.commonChange('main.blacklistModel', true);
                  return;
                }
                Taro.navigateTo({
                  url: '/pages/package-C/points-mall/record/index',
                });
              }}
            >
              <Image className="calendarImg" src={goldImg} mode="widthFix" />
              <View className="text">{pointsAvailable} 积分</View>
            </View>
          </View>

          {/* {show && (
            <View className="message">
              <Text className="title">关注公众号接收重要通知</Text>
              <View style={{flexDirection: 'row'}}>
                <View
                  className="center"
                  // onClick={() => {
                  // }}
                >
                  <Text className="open">去开启</Text>
                </View>
                <View
                  className="center"
                  onClick={() => {
                    this.setState({show: false});
                  }}
                >
                  <Image className="msClose" src={msClose} mode="widthFix" />
                </View>
              </View>
            </View>
          )} */}

          {/* 显示 && 蓝晶会员 || 赤晶会员 */}
          {showTip && ((isAquamarineMember && !isCrystalMember) || (!isAquamarineMember && isCrystalMember)) && (
            <View
              className={
                !isAquamarineMember && isCrystalMember ? 'isAquamarineMember tipBox' : 'isCrystalMember tipBox'
              }
            >
              <View className="center">
                <Image className="vipImg" src={vipImg} mode="widthFix" />
              </View>
              <View className="title">
                {!isAquamarineMember && isCrystalMember ? '吃喝玩乐嗨FUN季 优惠享不停！' : '社区福利 专属折扣享不停！'}
              </View>
              <View style={{flexDirection: 'row'}}>
                <View
                  className="center"
                  onClick={(e) => {
                    e.stopPropagation();
                    if (Taro.getStorageSync('blacklistModel')) {
                      action.commonChange('main.blacklistModel', true);
                      return;
                    }
                    Taro.navigateTo({
                      url: `/pages/package-A/memberOpen/index?type=${isAquamarineMember && !isCrystalMember ? 1 : 2}`,
                    });
                  }}
                >
                  <Text className="open">去查看</Text>
                </View>
                <View
                  className="center"
                  onClick={() => {
                    this.setState({showTip: false});
                  }}
                >
                  <Image className="msClose" src={msClose} mode="widthFix" />
                </View>
              </View>
            </View>
          )}
        </View>
        <TopBox />
        {/* <CenterBox /> */}
        <OrderBox />
        <ToolsBox />
        <AtModal
          isOpened={visible}
          onClose={() => {
            this.props.actions.action.commonChange('main.visible', false);
          }}
        >
          <AtModalContent>
            <View>
              <Text
                style={{
                  fontSize: '32rpx',
                  color: '#333',
                  letterSpacing: '2rpx',
                  textAlign: 'center',
                  marginTop: '10rpx',
                }}
              >
                客服热线
              </Text>
            </View>
            <View>
              <Text
                style={{
                  fontSize: '28rpx',
                  color: '#666666',
                  textAlign: 'center',
                  letterSpacing: '2rpx',
                  marginTop: '30rpx',
                }}
              >
                400-875-0222
              </Text>
            </View>
            <View
              style={{
                marginTop: '50rpx',
                alignItems: 'center',
              }}
            >
              <View
                style={{borderRadius: '30px', overflow: 'hidden'}}
                onClick={() => {
                  this.props.actions.action.commonChange('main.visible', false);
                  Taro.makePhoneCall({phoneNumber: '4008750222'});
                }}
              >
                <Text className="call">立即拨打</Text>
              </View>
              <View
                onClick={() => {
                  this.props.actions.action.commonChange('main.visible', false);
                }}
              >
                <Text className="cencel">取消</Text>
              </View>
            </View>
          </AtModalContent>
        </AtModal>
        <BlacklistModel
          isOpened={blacklistModel}
          onConfirm={() => {
            action.commonChange('main.blacklistModel', false);
          }}
          onCancel={() => {
            action.commonChange('main.blacklistModel', false);
          }}
        />
        <View style={{height: '1px'}}></View>
        <AdvModal
          imgUrl={this.state.imgUrl}
          handleUrl={() => handleUrl(this.state.jumpPage)}
          handleClose={() => this.handleClose()}
          isModalFlag={this.state.isModalFlag}
        />
      </ScrollView>
    );
  }
}

//create by moon https://github.com/creasy2010/moon
